import React, { FC, useEffect } from 'react';
import { FormInstance } from 'antd/lib/form';
import ProTable, { ProColumns } from '@/components/ProTable';
import { useUnmount } from 'ahooks';
import { PlanListReturnType } from '../../API';
import Week from './Week';
import useHoxModel from '../../useHoxModel';
import { pick } from 'lodash';
import moment from 'moment';

const AddForm: FC<{ formRef: React.MutableRefObject<FormInstance | undefined> }> = ({
  formRef,
}) => {
  const { planModeInfo, dispatch } = useHoxModel((model) => [model.planModeInfo]);
  useUnmount(() => {
    formRef.current?.resetFields();
    dispatch({ planModeInfo: {} });
  });
  useEffect(() => {
    if (planModeInfo && JSON.stringify(planModeInfo) !== '{}') {
      const completionTime = (time: any) => {
        return '2020-01-01 ' + time + ':00';
      };

      let fields = pick(planModeInfo, ['name', 'selDayInfo', 'rec']);
      fields['time'] = [
        moment(completionTime(planModeInfo.startTime)),
        moment(completionTime(planModeInfo.endTime)),
      ];
      formRef.current?.setFieldsValue(fields);
    }
  }, [planModeInfo]);

  const columns: ProColumns<PlanListReturnType>[] = [
    {
      title: '模板名称:',
      rules: [
        {
          required: true,
        },
      ],
      dataIndex: 'name',
    },
    {
      title: '周期选择:',
      rules: [
        {
          required: true,
        },
      ],
      dataIndex: 'selDayInfo',
      renderFormItem: () => (
        <Week
          onChange={(value) => {
            formRef.current?.setFieldsValue({
              selDayInfo: value,
            });
          }}
        />
      ),
    },
    {
      title: '时间段:',
      dataIndex: 'time',
      rules: [
        {
          required: true,
        },
      ],
      formItemProps: {
        picker: 'time',
        format: 'HH:mm',
      },
      valueType: 'dateTimeRange',
    },
    {
      title: '备注:',
      dataIndex: 'rec',
      valueType: 'textarea',
    },
  ];

  return (
    <>
      <ProTable<PlanListReturnType>
        form={{
          layout: 'vertical',
          autoComplete: 'off',
        }}
        columns={columns}
        type={'form'}
        formRef={formRef}
      />
    </>
  );
};
export default AddForm;
